package com.exam.controller;

import com.exam.pojo.ApiResult;
import com.exam.pojo.PaperManage;
import com.exam.service.FillQuestionService;
import com.exam.service.JudgeQuestionService;
import com.exam.service.MultiQuestionService;
import com.exam.service.PaperService;
import com.exam.util.ApiResultHandler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.exam.vo.Item;
import java.util.List;

@RestController
public class


ItemController {
    @Autowired
    private FillQuestionService fillQuestionService;
    @Autowired
    private MultiQuestionService multiQuestionService;
    @Autowired
    private JudgeQuestionService judgeQuestionService;
    @Autowired
    private PaperService paperService;
    @PostMapping("/item")
    public ApiResult ItemController(@RequestBody Item item){
        Integer changeNumber = item.getChangeNumber();
        Integer fillNumber = item.getFillNumber();
        Integer judgeNumber = item.getJudgeNumber();
        Integer paperId = item.getPaperId();
        List<Integer> changeNumbers=multiQuestionService.findBySubject(item.getSubject(),changeNumber);
        if(changeNumbers==null){
            return ApiResultHandler.buildApiResult(400, "选择题库获取失败", null);
        }
        for (Integer number:changeNumbers){
            PaperManage paperManage = new PaperManage(paperId, 1, number);
            int index=paperService.add(paperManage);
            if (index==0) {
                return ApiResultHandler.buildApiResult(400, "选择题组卷保存失败", null);
            }
        }
        List<Integer> fills=fillQuestionService.findBySubject(item.getSubject(),fillNumber);
        if (fills==null){
            return ApiResultHandler.buildApiResult(400, "填空题库获取失败", null);
        }
        for (Integer fillNum:fills){
            PaperManage paperManage = new PaperManage(paperId, 2, fillNum);
            int index=paperService.add(paperManage);
            if (index==0){
                return ApiResultHandler.buildApiResult(400, "填空题组卷失败", null);
            }
        }
        List<Integer> judges=judgeQuestionService.findBySubject(item.getSubject(),judgeNumber);
        if(judges==null){
            return ApiResultHandler.buildApiResult(400, "判断题库获取失败", null);
        }
        for (Integer judgeNum:judges){
            PaperManage paperManage = new PaperManage(paperId, 3, judgeNum);
            int index=paperService.add(paperManage);
            if (index==0){
                return ApiResultHandler.buildApiResult(400, "判断题组卷失败", null);
            }
        }
        return ApiResultHandler.buildApiResult(200, "组卷成功", null);
    }
}
